from django.contrib.auth.models import Permission, ContentType, Group
from users.models import User
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet

from meiduo_admin.serializers.permission import PermissionPermsSerializer, PermissionContentTypesSerializer, \
    PermissionGroupsSerializer, PermissionAdminsSerializer, PermissionSimpleSerializer, PermissionGroupsSimpleSerializer
from meiduo_admin.utils import PageNum


class PermissionPermsModelViewSet(ModelViewSet):
    """获取用户权限表列表数据"""
    serializer_class = PermissionPermsSerializer

    # 分页类
    pagination_class = PageNum

    def get_queryset(self):
        # 提取keyword
        keyword = self.request.query_params.get('keyword')

        if keyword == '' or keyword is None:
            return Permission.objects.all().order_by('id')

        else:
            return Permission.objects.filter(id=keyword).order_by('id')


# 获取权限类型列表数据
class PermissionContentTypesView(ListAPIView):
    serializer_class = PermissionContentTypesSerializer
    queryset = ContentType.objects.all()


# 分组表管理
class PermissionGroupsModelViewSet(ModelViewSet):
    serializer_class = PermissionGroupsSerializer
    # 分页类
    pagination_class = PageNum

    def get_queryset(self):
        # 提取keyword
        keyword = self.request.query_params.get('keyword')

        if keyword == '' or keyword is None:
            return Group.objects.all().order_by('id')

        else:
            return Group.objects.filter(id=keyword).order_by('id')


# 管理员表管理
class PermissionAdminsModelViewSet(ModelViewSet):
    serializer_class = PermissionAdminsSerializer
    queryset = User.objects.filter(is_superuser=True).order_by('id')
    # 分页类
    pagination_class = PageNum

    # def get_queryset(self):
    #     # 提取pk
    #     pk = self.kwargs.get('pk', None)
    #
    #     if pk is None:
    #         return User.objects.filter(is_superuser=True).order_by('id')
    #     # else:
    #     #     return User.objects.filter(id=pk).order_by('id')


# 获取权限表数据
class PermissionSimpleView(ListAPIView):
    serializer_class = PermissionSimpleSerializer
    queryset = Permission.objects.all().order_by('id')


# 获取分组表数据
class PermissionGroupsSimpleView(ListAPIView):
    serializer_class = PermissionGroupsSimpleSerializer
    queryset = Group.objects.all()
